package cn.stylefeng.guns.modular.business.frequency.appmessage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.app.controller.vo.PageBasic;
import cn.stylefeng.guns.modular.business.app.controller.vo.UserVo;
import cn.stylefeng.guns.modular.business.custom.constant.PublicCommon;
import cn.stylefeng.guns.modular.business.frequency.appmessage.entity.AppMessage;
import cn.stylefeng.guns.modular.business.frequency.appmessage.enums.AppMessageExceptionEnum;
import cn.stylefeng.guns.modular.business.frequency.appmessage.mapper.AppMessageMapper;
import cn.stylefeng.guns.modular.business.frequency.appmessage.model.param.AppMessageParam;
import cn.stylefeng.guns.modular.business.frequency.appmessage.service.AppMessageService;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.modular.business.util.PushToSingle;
import cn.stylefeng.guns.sys.modular.user.entity.SysUser;
import cn.stylefeng.guns.sys.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 系统消息表 服务实现类
 *
 * @author 刘耀
 * @date 2022/02/01 11:05
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class AppMessageServiceImpl extends ServiceImpl<AppMessageMapper, AppMessage> implements AppMessageService {

//    @Autowired
//    private MasterWorkerMapper masterWorkerMapper;
//    @Autowired
//    private PushGoeasyUtil pushGoeasyUtil;
//    @Autowired
//    private CustomerMapper customerMapper;
//    @Autowired
//    private OrderMessageMapper orderMessageMapper;
//    @Autowired
//    private UserMessageService userMessageService;

    @Resource
    private BusinessUtil businessUtil;


    @Override
    public PageResult<AppMessage> page(AppMessageParam appMessageParam) {
        appMessageParam.setTenantId(businessUtil.getTenantId());
        //获取当前登录人权限
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        if(empByOrgList!=null&&empByOrgList.size()==0){
            empByOrgList.add(-1l);
        }
        appMessageParam.setDataList(empByOrgList);
        if(businessUtil.getSiteId()!=null){
            appMessageParam.setSiteId(businessUtil.getSiteId());
        }else {
            appMessageParam.setSiteId(-1l);
        }
        Page<AppMessage> page = this.baseMapper.getPage(PageFactory.defaultPage(),appMessageParam);
        //获取分页结果
        List<AppMessage> appMessageList = page.getRecords();
        //根据订单id去重
        appMessageList = appMessageList.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(AppMessage::getOrderId))), ArrayList::new));
        //然后将去重结果存入Page中
        page.setRecords(appMessageList);
        // 查询分页结果
        return new PageResult<>(page);
    }

    @Override
    public List<AppMessage> list(AppMessageParam appMessageParam) {
        // 构造条件
        LambdaQueryWrapper<AppMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppMessage::getDelFlag, PublicCommon.启用);
        queryWrapper.eq(AppMessage::getTenantId, businessUtil.getTenantId());
        queryWrapper.eq(AppMessage::getMessageType, appMessageParam.getMessageType());
        queryWrapper.orderByDesc(AppMessage::getCreateTime);
        return this.list(queryWrapper);
    }

    @Resource
    private PushToSingle pushToSingle;
    @Resource
    private SysUserService sysUserService;

    @Override
    public void add(AppMessageParam appMessageParam) {
        // 将dto转为实体
        AppMessage appMessage = new AppMessage();
        BeanUtil.copyProperties(appMessageParam, appMessage);
        //if (appMessageParam.getIsRead() == 2) {
        //    //发送消息
        //    sendMessage(appMessage);
        //}
        this.save(appMessage);

//        查询租户的所有账号
        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getTenantId, appMessageParam.getTenantId()));

//        //推送消息
        sendThreadMessage(list, appMessage);
    }

    @Override
    public void publish(AppMessageParam appMessageParam) {

        //boolean update = this.update().set("has_release", 2)
        //        .set("release_time", new Date())
        //        .eq("id", appMessageParam.getId())
        //        .eq("has_release", 1)
        //        .update();
        //
        //if (update) {
        //    AppMessage appMessage = this.getById(appMessageParam.getId());
        //    //发送消息
        //    sendMessage(appMessage);
        //}
    }

    @Override
    public void deleteByOrderId(Long orderId) {
        Wrappers.<AppMessage>lambdaUpdate()
                .eq(AppMessage::getOrderId, orderId)
                .set(AppMessage::getDelFlag, 3);
    }

    public void sendMessage(AppMessage entity) {

//        List<UserVo> sendUserList = new ArrayList<>();
//        //userType 用户类型 -1 全部 1 用户 2全部咨询
//        //messageType 1 针对单个用户 2 针对部分用户 3 针对所有用户
//        if (entity.getUserType() == -1) {
//            List<Customer> customers = customerMapper.selectList(new QueryWrapper<Customer>().lambda()
//                    .eq(Customer::getCloseMessage, 1)//推送是否关闭;1 不关闭2  关闭
//                    .ne(Customer::getDelFlag, PublicCommon.删除));
//            if (customers.size() > 0) {
//                customers.stream().forEach(s -> {
//                    sendUserList.add(new UserVo(PublicCommon.用户, s.getId()));
//                });
//            }
//
//            List<MasterWorker> masterWorkers = masterWorkerMapper.selectList(new QueryWrapper<MasterWorker>().lambda()
//                    .eq(MasterWorker::getCloseMessage, 1)//推送是否关闭;1 不关闭2  关闭
//                    .ne(MasterWorker::getDelFlag, PublicCommon.删除));
//            if (masterWorkers.size() > 0) {
//                masterWorkers.stream().forEach(s -> {
//                    sendUserList.add(new UserVo(PublicCommon.咨询, s.getId()));
//                });
//            }
//
//        } else if (entity.getUserType() == 1) {
//            List<Customer> customers = customerMapper.selectList(new QueryWrapper<Customer>().lambda()
//                    .in(entity.getMessageType() != 3, Customer::getId, entity.getUserIds().split(","))
//                    .eq(Customer::getCloseMessage, 1)//推送是否关闭;1 不关闭2  关闭
//                    .ne(Customer::getDelFlag, PublicCommon.删除));
//            if (customers.size() > 0) {
//                customers.stream().forEach(s -> {
//                    sendUserList.add(new UserVo(PublicCommon.用户, s.getId()));
//                });
//            }
//        } else if (entity.getUserType() == 2) {
//            List<MasterWorker> masterWorkers = masterWorkerMapper.selectList(new QueryWrapper<MasterWorker>().lambda()
//                    .in(entity.getMessageType() != 3, MasterWorker::getId, entity.getUserIds().split(","))
//                    .eq(MasterWorker::getCloseMessage, 1)//推送是否关闭;1 不关闭2  关闭
//                    .ne(MasterWorker::getDelFlag, PublicCommon.删除));
//            if (masterWorkers.size() > 0) {
//                masterWorkers.stream().forEach(s -> {
//                    sendUserList.add(new UserVo(PublicCommon.咨询, s.getId()));
//                });
//            }
//        }
//        //推送消息
//        sendThreadMessage(sendUserList, entity.getTitle(), entity.getContent());
    }

    @Async("pushToSingle")
    public void sendThreadMessage(List<SysUser> sendUserList, AppMessage appMessage) {
        if (sendUserList.size() > 0) {
            sendUserList.stream().filter(new Predicate<SysUser>() {
                @Override
                public boolean test(SysUser sysUser) {
                    return StringUtils.isNotBlank(sysUser.getClientId());
                }
            }).forEach(s -> {
                //系统消息推送 用户
                pushToSingle.sendToAlias(null, appMessage.getMessageType(), appMessage.getTitle(), appMessage.getContent(), s.getClientId(), appMessage.getOrderId(), appMessage.getId(), 1);
            });
        }

    }

    @Override
    public void delete(AppMessageParam appMessageParam) {
        AppMessage appMessage = this.getById(appMessageParam.getId());
        if (ObjectUtil.isEmpty(appMessage)) {
            throw new ServiceException(AppMessageExceptionEnum.NOT_EXISTED);
        }
        appMessage.setDelFlag(appMessageParam.getDelFlag());
        this.updateById(appMessage);
    }

    @Override
    public void edit(AppMessageParam appMessageParam) {

        // 根据id查询实体
        AppMessage appMessage = this.queryAppMessage(appMessageParam);

        //if (appMessage.get() == 1 && appMessageParam.getHasRelease() == 2) {
        //    appMessage.setReleaseTime(new Date());
        //    //发送消息
        //    sendMessage(appMessage);
        //}
        // 请求参数转化为实体
        BeanUtil.copyProperties(appMessageParam, appMessage);

        this.updateById(appMessage);
    }

    @Override
    public AppMessage detail(Long appMessageId) {
        AppMessage appMessage = this.baseMapper.detail(appMessageId);
        if (ObjectUtil.isEmpty(appMessage)) {
            throw new ServiceException(AppMessageExceptionEnum.NOT_EXISTED);
        }
        return appMessage;
    }

    @Override
    public ResponseData messageCenter(UserVo user) {
//        //获取用户的创建时间
//        Date createTime = new Date();
//        if (user.getUserType() == 1) {
//            Customer customer = customerMapper.selectById(user.getUserId());
//            createTime = customer.getCreateTime();
//        }
//        //未读的系统消息数量
//        Integer systemMessageCount = baseMapper.messageCenter(user.getUserType(), user.getUserId(), createTime);
//        //最新的一条系统消息
//        AppMessage systemMessage = baseMapper.newMessage(user.getUserType(), user.getUserId(), createTime);
//
//        //未读的订单消息数量
//        Integer orderMessageCount = orderMessageMapper.selectCount(new QueryWrapper<OrderMessage>().lambda()
//                .eq(OrderMessage::getUserType, user.getUserType())
//                .eq(OrderMessage::getUserId, user.getUserId())
//                .eq(OrderMessage::getIsRead, PublicCommon.未读)
//                .eq(OrderMessage::getDelFlag, PublicCommon.启用));
//        //最新的一条订单消息
//        OrderMessage orderMessage = orderMessageMapper.selectOne(new QueryWrapper<OrderMessage>().lambda()
//                .eq(OrderMessage::getUserType, user.getUserType())
//                .eq(OrderMessage::getUserId, user.getUserId())
//                .eq(OrderMessage::getIsRead, PublicCommon.未读)
//                .eq(OrderMessage::getDelFlag, PublicCommon.启用).orderByDesc(BaseEntity::getCreateTime).last("limit 1"));
//
        Map<String, Object> result = new HashMap<>();
//
//        //系统未读消息数量
//        result.put("systemMessageCount", systemMessageCount);
//        //最新一条系统消息
//        result.put("systemMessage", systemMessage);
//
//        //订单未读消息数量
//        result.put("orderMessageCount", orderMessageCount);
//        //最新一条订单消息
//        result.put("orderMessage", orderMessage);

        return ResponseData.success(result);
    }

    @Override
    public ResponseData messageList(UserVo user, PageBasic req) {
        Page<AppMessage> appMessagePage = baseMapper.messagePage(new Page<>(req.getPageNo(), req.getPageSize()), user.getUserType(), user.getUserId());
//        if (appMessagePage.getRecords().size() > 0) {
//            List<UserMessage> userAppMessages = new ArrayList<>();
//            for (AppMessage appMessage : appMessagePage.getRecords()) {
//                if (appMessage.getIsRead() == 1) {
//                    appMessage.setIsRead(2);
//                    UserMessage userAppMessage = new UserMessage();
//                    userAppMessage.setDelFlag(PublicCommon.启用);
//                    userAppMessage.setUserId(user.getUserId());
//                    userAppMessage.setUserType(user.getUserType());
//                    userAppMessage.setMessageId(appMessage.getId());
//                    userAppMessages.add(userAppMessage);
//                }
//            }
//            if (userAppMessages.size() > 0) {
//                userMessageService.saveBatch(userAppMessages);
//            }
//        }
        return ResponseData.success(new PageResult<>(appMessagePage));
    }

    @Override
    public ResponseData clearList(List<Long> messageIds, UserVo user) {

        List<AppMessage> appMessageList = baseMapper.messageList(messageIds, user.getUserType(), user.getUserId());

//        if (appMessageList.size() > 0) {
//            List<UserMessage> userAppMessages = new ArrayList<>();
//            for (AppMessage appMessage : appMessageList) {
//                if (appMessage.getUserMessageId() == null) {
//                    UserMessage userAppMessage = new UserMessage()
//                            .setDelFlag(PublicCommon.启用)
//                            .setUserId(user.getUserId())
//                            .setUserType(user.getUserType())
//                            .setMessageId(appMessage.getId())
//                            .setIsShow(2);
//                    userAppMessages.add(userAppMessage);
//                } else {
//                    UserMessage byId = new UserMessage();
//                    byId.setId(appMessage.getUserMessageId());
//                    byId.setIsShow(2);
//                    userAppMessages.add(byId);
//                }
//            }
//            if (userAppMessages.size() > 0) {
//                userMessageService.saveOrUpdateBatch(userAppMessages);
//            }
//        }
        return ResponseData.success();
    }

    /**
     * 获取系统消息表
     *
     * @author 刘耀
     * @since 2022/02/01 11:05
     */
    private AppMessage queryAppMessage(AppMessageParam appMessageParam) {
        AppMessage appMessage = this.getById(appMessageParam.getId());
        if (ObjectUtil.isEmpty(appMessage)) {
            throw new ServiceException(AppMessageExceptionEnum.NOT_EXISTED);
        }
        return appMessage;
    }
}